package com.example.studentknowledge.service;

import com.example.studentknowledge.entity.Follow;
import com.example.studentknowledge.entity.User;
import com.example.studentknowledge.repository.FollowRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 关注服务类
 */
@Service
@Transactional
public class FollowService {
    
    @Autowired
    private FollowRepository followRepository;
    
    /**
     * 关注用户
     */
    public Follow followUser(User follower, User followed) {
        // 检查是否已经关注
        if (followRepository.existsByFollowerAndFollowed(follower, followed)) {
            throw new RuntimeException("已经关注过该用户");
        }
        
        // 不能关注自己
        if (follower.getId().equals(followed.getId())) {
            throw new RuntimeException("不能关注自己");
        }
        
        Follow follow = new Follow();
        follow.setFollower(follower);
        follow.setFollowed(followed);
        
        return followRepository.save(follow);
    }
    
    /**
     * 取消关注
     */
    public void unfollowUser(User follower, User followed) {
        Optional<Follow> follow = followRepository.findByFollowerAndFollowed(follower, followed);
        if (follow.isPresent()) {
            followRepository.delete(follow.get());
        }
    }
    
    /**
     * 切换关注状态
     */
    public boolean toggleFollow(User follower, User followed) {
        Optional<Follow> follow = followRepository.findByFollowerAndFollowed(follower, followed);
        
        if (follow.isPresent()) {
            // 已关注，取消关注
            followRepository.delete(follow.get());
            return false;
        } else {
            // 未关注，添加关注
            followUser(follower, followed);
            return true;
        }
    }
    
    /**
     * 检查是否关注了某用户
     */
    public boolean isFollowing(User follower, User followed) {
        return followRepository.existsByFollowerAndFollowed(follower, followed);
    }
    
    /**
     * 获取用户的关注列表（我关注的人）
     */
    public Page<Follow> getFollowing(User follower, Pageable pageable) {
        return followRepository.findByFollowerOrderByCreatedAtDesc(follower, pageable);
    }
    
    /**
     * 获取用户的粉丝列表（关注我的人）
     */
    public Page<Follow> getFollowers(User followed, Pageable pageable) {
        return followRepository.findByFollowedOrderByCreatedAtDesc(followed, pageable);
    }
    
    /**
     * 获取用户关注的用户列表
     */
    public List<User> getFollowingUsers(User follower, Pageable pageable) {
        return followRepository.findFollowingUsers(follower, pageable);
    }
    
    /**
     * 获取用户的粉丝用户列表
     */
    public List<User> getFollowerUsers(User followed, Pageable pageable) {
        return followRepository.findFollowerUsers(followed, pageable);
    }
    
    /**
     * 统计用户的关注数
     */
    public Long countFollowing(User follower) {
        return followRepository.countFollowing(follower);
    }
    
    /**
     * 统计用户的粉丝数
     */
    public Long countFollowers(User followed) {
        return followRepository.countFollowers(followed);
    }
    
    /**
     * 根据ID查找关注关系
     */
    public Optional<Follow> findById(Long id) {
        return followRepository.findById(id);
    }
    
    /**
     * 删除关注关系
     */
    public void deleteFollow(Long id) {
        followRepository.deleteById(id);
    }
    
    /**
     * 批量删除用户的所有关注关系（作为关注者）
     */
    public void deleteUserFollowing(User follower) {
        followRepository.deleteByFollower(follower);
    }
    
    /**
     * 批量删除用户的所有粉丝关系（作为被关注者）
     */
    public void deleteUserFollowers(User followed) {
        followRepository.deleteByFollowed(followed);
    }
    
    /**
     * 获取互相关注的用户（好友）
     */
    public List<User> getMutualFollows(User user, Pageable pageable) {
        List<User> following = getFollowingUsers(user, pageable);
        List<User> followers = getFollowerUsers(user, pageable);
        
        // 找出既在关注列表又在粉丝列表中的用户
        following.retainAll(followers);
        return following;
    }
    
    /**
     * 检查两个用户是否互相关注
     */
    public boolean isMutualFollow(User user1, User user2) {
        return isFollowing(user1, user2) && isFollowing(user2, user1);
    }
}